import Cookies from 'js-cookie'
import config from '@/config'
import wx from 'weixin-js-sdk'
import store from '../store'
import { getSdkConfig, getPayOptions, getMediaToOss } from '../api/wx-api'

export const TOKEN_KEY = 'token'
export const WXCONFIG = 'wx-config'

const { cookieExpires } = config

export const setToken = (token) => {
  Cookies.set(TOKEN_KEY, token, { expires: cookieExpires || 1 })
  if (token === '' || token === undefined) {
    console.log('晴空cookies')
    clearCookies()
  }
}

export const getToken = () => {
  const token = Cookies.get(TOKEN_KEY)
  if (token) return token
  else return false
}
export const clearCookies = () => {
  Cookies.remove('juyou.session.id')
}

export const wxConfig = (data) => {
  if (data === '' || data === undefined) {
    const wxConfig = Cookies.get(WXCONFIG)
    if (wxConfig) return JSON.parse(wxConfig)
    else return false
  } else {
    Cookies.set(WXCONFIG, JSON.stringify(data), { expires: cookieExpires || 1 })
  }
}

/**
 * @param {Array} routeMetched 当前路由metched
 * @returns {Array}
 */
export const getBreadCrumbList = (route, homeRoute) => {
  console.log(route, homeRoute, '执行函数')
  let homeItem = { ...homeRoute, icon: homeRoute.meta.icon }
  let routeMetched = route.matched
  if (routeMetched.some(item => item.name === homeRoute.name)) return [homeItem]
  let res = routeMetched.filter(item => {
    return item.meta === undefined || !item.meta.hideInBread
  }).map(item => {
    let meta = { ...item.meta }
    if (meta.title && typeof meta.title === 'function') {
      meta.__titleIsFunction__ = true
      meta.title = meta.title(route)
    }
    let obj = {
      icon: (item.meta && item.meta.icon) || '',
      name: item.name,
      meta: meta
    }
    return obj
  })
  res = res.filter(item => {
    return !item.meta.hideInMenu
  })
  return [{ ...homeItem, to: homeRoute.path }, ...res]
}
/**
 * @param {Array} routers 路由列表数组
 * @description 用于找到路由列表中name为home的对象
 */
export const getHomeRoute = (routers, homeName = 'home') => {
  let i = -1
  let len = routers.length
  let homeRoute = {}
  while (++i < len) {
    let item = routers[i]
    if (item.children && item.children.length) {
      let res = getHomeRoute(item.children, homeName)
      if (res.name) return res
    } else {
      if (item.name === homeName) homeRoute = item
    }
  }
  return homeRoute
}

export const showTitle = (item, vm) => {
  let { title } = item.meta
  if (!title) return
  title = (item.meta && item.meta.title) || item.name
  return title
}

export const phpMenusfilter = (data) => {
  return data
}
export const javaMenusfilter = (data) => {
  return data
}
export const wxCallBack = (fun) => {
  let resultData = wxConfig('')
  const url = window.location.href
  const resultUrl = url.substr(0, url.indexOf('#') - 1)
  const g = false
  if (resultData !== false && resultUrl === resultData.url && g) {
    wxJsConfig(resultData, fun)
  } else {
    getSdkConfig().then(ret => {
      let resultData = ret.data
      resultData.url = resultUrl
      wxConfig(resultData)
      wxJsConfig(resultData, fun)
    })
  }
}
export const wxJsConfig = (resultData, fun) => {
  const jsApiList = ['showMenuItems', 'addCard', 'hideAllNonBaseMenuItem', 'getLocalImgData', 'downloadImage', 'chooseWXPay', 'chooseImage', 'onMenuShareAppMessage', 'onMenuShareTimeline', 'uploadImage', 'previewImage', 'getLocation', 'openLocation', 'hideMenuItems', 'scanQRCode', 'editAddress', 'startRecord', 'stopRecord', 'uploadVoice', 'updateAppMessageShareData', 'updateTimelineShareData']
  wx.config({
    debug: config.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId: resultData.data.appId, // 必填，公众号的唯一标识
    timestamp: resultData.data.timestamp, // 必填，生成签名的时间戳
    nonceStr: resultData.data.nonceStr, // 必填，生成签名的随机串
    signature: resultData.data.signature, // 必填，签名，见附录1
    jsApiList: jsApiList
  })
  wx.ready(fun)
}

export const commonShare = (options) => {
  share({
    title: '沈阳经济区市民卡',
    desc: '专项补贴、专享福利、专属保障',
    link: config.baseUrl + '/#/common-share',
    imgurl: 'https://skv4.oss-cn-hangzhou.aliyuncs.com/cityCard/project/city-card-share.png'
  })
}

export const share = (options) => {
  wxCallBack(function () {
    wx.updateAppMessageShareData({
      title: options.title, // 分享标题
      desc: options.desc, // 分享描述
      link: options.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: options.imgurl, // 分享图标
      success: function () {
        if (typeof options.success === 'function') {
          options.success()
        }
      }
    })
    wx.updateTimelineShareData({
      title: options.title, // 分享标题
      link: options.link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: options.imgurl, // 分享图标
      success: function () {
        if (typeof options.success === 'function') {
          options.success()
        }
      }
    })
  })
}

export const getLocation = (fun) => {
  wxCallBack(function () {
    wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: function (res) {
        fun(res)
      }
    })
  })
}

export const openAddress = (fun) => {
  wxCallBack(function () {
    wx.openAddress({
      success: function (res) {
        fun(res)
      }
    })
  })
}
export const openLocation = (options) => {
  wxCallBack(function () {
    wx.openLocation({
      latitude: options.latitude, // 纬度，浮点数，范围为90 ~ -90
      longitude: options.longitude, // 经度，浮点数，范围为180 ~ -180。
      name: options.name, // 位置名
      address: options.address, // 地址详情说明
      scale: 20, // 地图缩放级别,整形值,范围从1~28。默认为最大
      infoUrl: options.url // 在查看位置界面底部显示的超链接,可点击跳转
    })
  })
}

export const loginOther = (fun) => {
  getJuYouToken().then(ret => {
    if (ret.data.errcode === 0) {
      let code = ret.data.data
      let data = {
        code: code
      }
      loginForCTC(data, function (ret, url) {
        let obj = {}
        obj[url] = ret.data.data.key
        store.dispatch('setTicket', obj)
        fun()
      })
    } else {
      Notify({
        message: ret.data.errmsg
      })
    }
  })
}

export const wxPay = (order, fun) => {
  getPayOptions(order).then(ret => {
    let data = ret.data
    if (data.status === 1) {
      WeixinJSBridge.invoke(
        'getBrandWCPayRequest', data.result,
        function (res) {
          if (res.err_msg === 'get_brand_wcpay_request:ok') { // 成功回调函数
            return fun(res, 'success')
          } else {
            var resData = res
            // 设置专用属性
            resData['hderrorcode'] = '-1'
            if (typeof (opt.error) === 'function') {
              return fun(resData, 'error')
            }
            if (res.err_msg === 'get_brand_wcpay_request:cancel') {
              this.$dialog.toast({
                mes: '支付取消！',
                timeout: 1500
              })
              if (typeof (opt.cancel) === 'function') {
                return fun(resData, cancel)
              }
            } else {
              this.$dialog.toast({
                mes: '支付失败' + res.err_msg,
                timeout: 1500
              })
            }
            return resData
          }
        }
      )
    } else if (data.status === 1201) {
      let self_url = window.location.href.replace(/#/g, '$')
      location.href = config.baseUrl + '/Api/Api/payJmAuth/cid/' + config.company_code + '?rurl=' + self_url
    } else {
      Toast.fail(data.msg)
    }
  })
}

export const isIos = () => {
  let equipmentType = ''
  let agent = navigator.userAgent.toLowerCase()
  let android = agent.indexOf('android')
  let iphone = agent.indexOf('iphone')
  let ipad = agent.indexOf('ipad')
  if (android !== -1) {
    equipmentType = false
  }
  if (iphone !== -1 || ipad !== -1) {
    equipmentType = true
  }
  return equipmentType
}
/**
 * TODO 目前只能传递一个图片，多个图片以后在做
 * @param option
 */
export const wxUploadImg = (option) => {
  option.num = option.num || 1
  option.num = option.num > 9 ? 9 : option.num
  if (option.type) {
    option.type = ['album', 'camera']
  }
  wxCallBack(function () {
    wx.chooseImage({
      count: option.num,
      sourceType: option.type,
      success: res => {
        let localIds001 = res.localIds
        wx.uploadImage({
          localId: localIds001[0], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: function (res1) {
            let serverId = res1.serverId// 返回图片的服务器端ID
            getMediaToOss(serverId).then(result => {
              option.success(result.data)
            })
          }
        })
      }
    })
  })
}

export const isEmpty = (data) => {
  if (data === '' || data === null || data === undefined || data === 'undefined') {
    return true
  } else {
    return false
  }
}

/**
 *
 * @param idCode {要验证的身份证号}
 * @param tipShow {是否打印错误信息，true打印}
 * @returns {boolean}
 */
export const identityCodeValid = (idCode, tipShow) => {
  // 消除空格
  let code = idCode
  if (code) {
    code = code.toString().trim()
    // 已#号替换x
    if (code.indexOf('#') > 0) {
      code = code.replace('#', 'X')
    }
  } else {
    return false
  }

  let city = {
    11: '北京',
    12: '天津',
    13: '河北',
    14: '山西',
    15: '内蒙古',
    21: '辽宁',
    22: '吉林',
    23: '黑龙江 ',
    31: '上海',
    32: '江苏',
    33: '浙江',
    34: '安徽',
    35: '福建',
    36: '江西',
    37: '山东',
    41: '河南',
    42: '湖北 ',
    43: '湖南',
    44: '广东',
    45: '广西',
    46: '海南',
    50: '重庆',
    51: '四川',
    52: '贵州',
    53: '云南',
    54: '西藏 ',
    61: '陕西',
    62: '甘肃',
    63: '青海',
    64: '宁夏',
    65: '新疆',
    71: '台湾',
    81: '香港',
    82: '澳门',
    91: '国外 '
  }
  let tip = ''
  let pass = true

  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    tip = '身份证号格式错误'
    pass = false
  } else if (!city[code.substr(0, 2)]) {
    tip = '地址编码错误'
    pass = false
  } else {
    // 18位身份证需要验证最后一位校验位
    if (code.length === 18) {
      code = code.split('')
      // ∑(ai×Wi)(mod 11)
      // 加权因子
      let factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      // 校验位
      let parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2]
      let sum = 0
      let ai = 0
      let wi = 0
      for (let i = 0; i < 17; i++) {
        ai = code[i]
        wi = factor[i]
        sum += ai * wi
      }

      let last = parity[sum % 11]
      // 身份证校验位
      let lastCode = code[17]
      if (!/^[0-9]*$/.test(last)) {
        last = last.toLowerCase()
      }
      if (!/^[0-9]*$/.test(lastCode)) {
        lastCode = lastCode.toLowerCase()
      }
      if (last.toString() !== lastCode) {
        tip = '校验位错误,最后以为应该是' + last
        pass = false
      }
    }
  }
  if (tipShow === true) {
    console.log(idCode, tip)
  }
  return pass
}
